package com.atguigu.eduservice.service.impl;

import com.atguigu.commonutils.R;
import com.atguigu.eduservice.client.VodClient;
import com.atguigu.eduservice.entity.EduChapter;
import com.atguigu.eduservice.entity.EduCourse;
import com.atguigu.eduservice.entity.EduCourseDescription;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.entity.frontvo.CourseFrontVo;
import com.atguigu.eduservice.entity.frontvo.CourseWebVo;
import com.atguigu.eduservice.entity.vo.CourseInfoVo;
import com.atguigu.eduservice.entity.vo.CoursePublishVo;
import com.atguigu.eduservice.mapper.EduCourseMapper;
import com.atguigu.eduservice.service.EduChapterService;
import com.atguigu.eduservice.service.EduCourseDescriptionService;
import com.atguigu.eduservice.service.EduCourseService;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.servicebase.exceptionhandler.SelfExceptionHandler;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2023-03-05
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    //描述
    @Autowired
    private EduCourseDescriptionService courseDescriptionService;

    @Autowired
    private EduChapterService chapterService;
    //小节
    @Autowired
    private EduVideoService videoService;

    @Autowired
    private VodClient vodClient;

    /**
     * 添加课程信息，返回课程id，前端需要
     * @param courseInfoVo
     * @return
     */
    public String addCourseInfo(CourseInfoVo courseInfoVo)
    {
        if(courseInfoVo!=null){
            EduCourse eduCourse=new EduCourse();
            BeanUtils.copyProperties(courseInfoVo,eduCourse);
            //将课程信息添加到数据库中
            int insert = baseMapper.insert(eduCourse);
            //将课程描述添加到课程描述表中
            EduCourseDescription description=new EduCourseDescription();
            BeanUtils.copyProperties(courseInfoVo,description);
            //共享id.des表的id是course的
            description.setId(eduCourse.getId());
            //引入课程表的service来添加
            boolean save = courseDescriptionService.save(description);
            return eduCourse.getId();
       }
       return null;
    }

    /**
     * 根据课程id查询，实现信息回显
     * @param courseId
     * @return
     */
    @Override
    public CourseInfoVo getCourseInfoByID(String courseId) {

        CourseInfoVo courseInfoVo=new CourseInfoVo();
        //课程基本信息
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        wrapper.eq("id",courseId);
        EduCourse eduCourse = baseMapper.selectOne(wrapper);
        BeanUtils.copyProperties(eduCourse,courseInfoVo);
        //课程描述
        QueryWrapper<EduCourseDescription> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id",courseId);
        EduCourseDescription courseDescriptionServiceOne = courseDescriptionService.getOne(queryWrapper);
        BeanUtils.copyProperties(courseDescriptionServiceOne,courseInfoVo);
        return courseInfoVo;
    }

    /**
     * 修改课程信息
     * @param courseInfoVo
     */
    @Override
    public boolean updateCourseInfo(CourseInfoVo courseInfoVo) {

        //修改课程表
        EduCourse eduCourse=new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        int update=baseMapper.updateById(eduCourse);
        if(update == 0) {
            throw new SelfExceptionHandler("修改课程信息失败",20001);
        }
        //修改课程描述表
        EduCourseDescription eduCourseDescription=new EduCourseDescription();
        eduCourseDescription.setId(courseInfoVo.getId());
        eduCourseDescription.setDescription(courseInfoVo.getDescription());
        courseDescriptionService.updateById(eduCourseDescription);
        return true;
    }

    /**
     * 根据课程id查询课程信息
     * @param courseId
     * @return
     */
    @Override
    public CoursePublishVo getCoursePublishVo(String courseId) {
        //使用baseMapper调用
        CoursePublishVo coursePublishVo = baseMapper.getCoursePublishVo(courseId);
        return coursePublishVo;
    }

    /**
     * 得到所有课程，列表展示，
     * @return
     */
    @Override
    public List<EduCourse> getCourseList() {

        LambdaQueryWrapper<EduCourse> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(EduCourse::getGmtModified);//按照最新时间降序
        List<EduCourse> courseList = baseMapper.selectList(wrapper);
        return courseList;
    }

    /**
     * 分页查询
     * @param current
     * @param limit
     * @return
     */
    @Override
    public Map<String, Object> pageList(long current, long limit) {
        Page<EduCourse> page = new Page<EduCourse>(current,limit);
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        //时间降序
        wrapper.orderByDesc("gmt_modified");
        page=(Page<EduCourse>) baseMapper.selectPage(page, wrapper);
        long total= page.getTotal();
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("total",total);
        map.put("items",page);
        return map;
    }

    /**
     * 条件查询带分页
     * @param current
     * @param limit
     * @param eduCourse
     * @return
     */
    @Override
    public Map<String, Object> pageConditionList(long current, long limit, EduCourse eduCourse) {

            LambdaQueryWrapper<EduCourse> wrapper = new LambdaQueryWrapper<>();
            wrapper.like(eduCourse.getTitle()!=null,EduCourse::getTitle,eduCourse.getTitle());
            wrapper.eq(eduCourse.getStatus()!=null,EduCourse::getStatus,eduCourse.getStatus());
            wrapper.orderByDesc(EduCourse::getGmtModified);
            Page<EduCourse> page = new Page<>(current, limit);
            page=( Page<EduCourse>) baseMapper.selectPage(page, wrapper);
            long total=page.getTotal();
            List<EduCourse> records = page.getRecords();//数据list集合
            HashMap<String, Object> map = new HashMap<>();
            map.put("total",total);
            map.put("records",records);
            return  map;


    }

    /**
     * 删除课程，依次删除 视频，小节，章节，描述，课程
     * @param courseId
     * @return
     */
    @Override
    public boolean removeCourse(String courseId) {
        //批量删除视频
        QueryWrapper<EduVideo> queryWrapper=new QueryWrapper();
        queryWrapper.eq("course_id",courseId);
        queryWrapper.select("video_source_id");
        List<EduVideo> list = videoService.list(queryWrapper);

        //得到视频批量id
        List<String> videoIdList=new ArrayList();
        for(EduVideo video:list)
        {
            if(video!=null)
            {
                if(video.getVideoSourceId()!=null)
                videoIdList.add(video.getVideoSourceId());
            }
        }

        //调用方法删除视频
       vodClient.removeVideoBatch(videoIdList);

        //2.删除小节
        videoService.remove(queryWrapper);
        //3.删除章节
        QueryWrapper<EduChapter> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        chapterService.remove(wrapper);

        //删除描述
         courseDescriptionService.removeById(courseId);
         //删除课程
        int i = baseMapper.deleteById(courseId);
        if(i==0)
        {
            throw new SelfExceptionHandler("删除课程失败",20001);
        }

        return true;
    }

    /**
     * 前8个课程显示，按照浏览量
     * @return
     */
    @Override
    public List<EduCourse> indexCourseInfo() {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("view_count");
        wrapper.last("limit 8");
        List<EduCourse> courseList = baseMapper.selectList(wrapper);
        return courseList;
    }

    /**
     * 讲师id查询课程
     * @param teacherId
     * @return
     */
    @Override
    public List<EduCourse> selectByTeacherId(String teacherId) {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        wrapper.eq("teacher_id",teacherId);
        //根据更新时间降序
        wrapper.orderByDesc("gmt_modified");
        List<EduCourse> courses = baseMapper.selectList(wrapper);
        return courses;
    }

    /**
     * 前台分页查询
     * @param
     * @param courseFrontVo
     * @return
     */
    @Override
    public Map<String, Object> getCourseFrontList(Page<EduCourse> pageParam, CourseFrontVo courseFrontVo) {
        //2 根据讲师id查询所讲课程
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        //判断条件值是否为空，不为空拼接
        if(!StringUtils.isEmpty(courseFrontVo.getSubjectParentId())) { //一级分类
            wrapper.eq("subject_parent_id",courseFrontVo.getSubjectParentId());
        }
        if(!StringUtils.isEmpty(courseFrontVo.getSubjectId())) { //二级分类
            wrapper.eq("subject_id",courseFrontVo.getSubjectId());
        }
        if(!StringUtils.isEmpty(courseFrontVo.getBuyCountSort())) { //关注度
            wrapper.orderByDesc("buy_count");
        }
        if (!StringUtils.isEmpty(courseFrontVo.getGmtCreateSort())) { //最新
            wrapper.orderByDesc("gmt_create");
        }

        if (!StringUtils.isEmpty(courseFrontVo.getPriceSort())) {//价格
            wrapper.orderByDesc("price");
        }

        baseMapper.selectPage(pageParam,wrapper);

        List<EduCourse> records = pageParam.getRecords();
        long current = pageParam.getCurrent();
        long pages = pageParam.getPages();
        long size = pageParam.getSize();
        long total = pageParam.getTotal();
        boolean hasNext = pageParam.hasNext();//下一页
        boolean hasPrevious = pageParam.hasPrevious();//上一页

        //把分页数据获取出来，放到map集合
        Map<String, Object> map = new HashMap<>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        //map返回
        return map;
    }


    //根据课程id，编写sql语句查询课程信息
    @Override
    public CourseWebVo getBaseCourseInfo(String courseId) {
        return baseMapper.getBaseCourseInfo(courseId);
    }

}
